package com.android.allwinner.newaw360;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.android.allwinner.newaw360.adapter.FileAdapter;
import com.android.allwinner.newaw360.media.MediaFileInfo;
import com.android.allwinner.newaw360.storage.AW360StorageManager;
import com.android.allwinner.newaw360.utils.AW360SharePreferenceUtil;
import com.android.allwinner.newaw360.utils.LogUtil;
import com.android.allwinner.newaw360.view.AWDialog;
import com.android.allwinner.newaw360.view.AWProgressDialog;

import java.io.File;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2017/8/1.
 */

public class FileListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,View.OnClickListener{
    private static final String TAG = FileListActivity.class.getSimpleName();
    private static final int OVER = 0;
    private static final int ALERT_DIALOG_FOR_DELETE = 0;
    private static final int WAIT_NO_BUSY = 1;
    private ListView mListView;
    private FileAdapter mFileAdapter;
    private Button mChoiceAll;
    private Button mDeleteButton;
    private Button mBackButton;
    private AWDialog mBvDialog;
    private List<MediaFileInfo> mCurMediaFileInfos;
    private AWProgressDialog mProgressDialog;
    private int mAlertDialogType = -1;
    private int mSelect_flag=1;
    private boolean isResuming;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case OVER:
                    dismissProgressDialog();
                    Iterator<MediaFileInfo> iterator = mCurMediaFileInfos
                            .iterator();
                    while (iterator.hasNext()) {
                        MediaFileInfo fileInfo = iterator.next();
                        if (fileInfo.isSelected()) {
                            iterator.remove();
                        }
                    }
                    if (isResuming) {
                        LogUtil.d(TAG, "--------handleMessage----OVER----notifyDataSetChanged");
                        mFileAdapter.notifyDataSetChanged();
                    }
                    mFileAdapter.mClearSaveSelect();
                    break;
                case WAIT_NO_BUSY:
                    new MediaFileTask().execute(0);
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_files);
        initView();
        new MediaFileTask().execute(0);
    }

    private void initView(){
        mListView = (ListView)findViewById(R.id.file_list_lv);
        mListView.setOnItemClickListener(this);
        mFileAdapter = new FileAdapter(this);
        mListView.setAdapter(mFileAdapter);
        mChoiceAll=(Button)findViewById(R.id.Choice_all);
        mChoiceAll.setOnClickListener(this);
        mDeleteButton = (Button)findViewById(R.id.delete_file_b);
        mDeleteButton.setOnClickListener(this);
        mBackButton=(Button) findViewById(R.id.back_file_b);
        mBackButton.setOnClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this,PlayActivity.class);
        String pathString = mFileAdapter.getItem(position).getPath();
        intent.putExtra(PlayActivity.KEY_PATH,pathString);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.delete_file_b:
                mAlertDialogType = ALERT_DIALOG_FOR_DELETE;
                if (getSelectCount() == 0) {
                    break;
                }
                showAlertDialog(R.string.deletevideo_alert_str);
                break;
            case R.id.back_file_b:
                finish();
                break;
            case R.id.Choice_all:
                if (mSelect_flag==1){
                    mFileAdapter.all_setSelected();
                    mFileAdapter.notifyDataSetChanged();
                    mSelect_flag=0;
                }
                else{
                    mFileAdapter.all_Cancel_Select();
                    mFileAdapter.notifyDataSetChanged();
                    mSelect_flag=1;
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResuming = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResuming = true;
    }

    private void deleteSelectFile() {
        showProgressDialog(getResources().getString(R.string.deleting_str));
        new Thread() {
            @Override
            public void run() {
                Iterator<MediaFileInfo> iterator = mCurMediaFileInfos.iterator();
                while (iterator.hasNext()) {
                    MediaFileInfo fileInfo = iterator.next();
                    if (fileInfo.isSelected()) {
                        /*LogUtil.d(TAG,"delete file "+fileInfo.getPath());*/
                        File file = new File(fileInfo.getPath());
                        file.delete();
                    }
                }
                mHandler.sendEmptyMessage(OVER);
            }
        }.start();
    }

    private int getSelectCount() {
        if (mCurMediaFileInfos == null || mCurMediaFileInfos.size() == 0) {
            return 0;
        }
        int count = 0;
        for (MediaFileInfo fileInfo : mCurMediaFileInfos) {
            if (fileInfo.isSelected()) {
                count++;
            }
        }
        return count;
    }

    private void showProgressDialog(String info) {
        if (mProgressDialog == null) {
            mProgressDialog = new AWProgressDialog(this);
        }

        if (mProgressDialog != null && !mProgressDialog.isShowing()) {
            mProgressDialog.show();
            mProgressDialog.setMessage(info);
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void showAlertDialog(int message) {
        if (mBvDialog == null) {
            mBvDialog = new AWDialog(this);
            mBvDialog.show();
            mBvDialog.setMessage(message);
            mBvDialog.setCancelable(false);
            mBvDialog.setNegativeListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mBvDialog.dismiss();
                }
            });
            mBvDialog.setPositiveListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    switch (mAlertDialogType) {
                        case ALERT_DIALOG_FOR_DELETE:
                            deleteSelectFile();
                            break;

                        default:
                            break;
                    }
                    mBvDialog.dismiss();
                }
            });
        }
        if(mBvDialog != null && !mBvDialog.isShowing()) {
            mBvDialog.show();
            mBvDialog.setMessage(message);
        }
    }

    class MediaFileTask extends AsyncTask<Integer, Integer, List<MediaFileInfo>> {
        public MediaFileTask() {

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<MediaFileInfo> doInBackground(Integer... params) {
            AW360StorageManager aw360StorageManager = new AW360StorageManager();
            mCurMediaFileInfos = aw360StorageManager.getVideoFiles(AW360SharePreferenceUtil.getVideoPath());
            return mCurMediaFileInfos;
        }

        @Override
        protected void onPostExecute(List<MediaFileInfo> result) {
            mFileAdapter.setMediaFiles(result);
            dismissProgressDialog();
            super.onPostExecute(result);
        }
    }
}
